import request  from 'umi-request';
import { notification, message } from 'antd';
import { getToken } from './auth';
import errorCode from '@/utils/errorCode';
import { getDvaApp } from 'umi';

// request interceptor, change url or options. 请求拦截器
request.interceptors.request.use((url, options) => {
  const isToken = (options.headers || {}).isToken === false;
  const renderHeaders = () => {
    if (getToken() && !isToken) {
      return { Authorization: 'Bearer ' + getToken() }; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
  };
  return {
    url: `${url}`,
    options: {
      ...options,
      interceptors: true,
      headers: renderHeaders(),
    },
  };
});

// handling error in response interceptor  响应拦截器
request.interceptors.response.use(async (response) => {
  console.log(response, 'reassesses');
  if (response?.status !== 200) {
    notification.warn({
      message: response?.status,
      description: `${response?.url}：${response?.status} ${response?.statusText}`,
    });
    return;
  }
  const data = await response.clone().json();
  // 未设置状态码则默认成功状态
  const code = data?.code || 200;
  // 获取错误信息
  const msg = errorCode[code] || data?.msg || errorCode.default;
  // 二进制数据则直接返回
  // if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
  //   return res.data
  // }
  if (code === 401) {
    message.warn('登录状态已过期');
    getDvaApp()._store.dispatch({
      type: 'login/logout',
    }).then(() => {
      location.replace('/user/login');
    });
    // return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
  } else if (code === 500) {
    message.error(msg);
    // return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    notification.warn({
      message: code,
      description: msg,
    });
    // return Promise.reject('error')
  } else {
    return response;
  }
});

const customizedRequest = (method, url, params, data, others = {}, noProxy = false) => {
  let urlPro
  if (url.startsWith('http')) {
    urlPro = url;
  } else {
    const prefix = noProxy ? '' : '/api';
    urlPro = `${prefix}${url}`;
  }

  return request(urlPro, {
    method,
    params,
    data,
    ...others,
  });
};

export default customizedRequest;
